<?php
/**
 * Created by PhpStorm.
 * User: PHP
 * Date: 2018/2/9
 * Time: 14:05
 */
namespace app\index\model;

use think\exception\PDOException;
use think\Model;

class Sign extends Model
{
    // 设置返回数据集的对象名
    protected $resultSetType = 'collection';
    protected $autoWriteTimestamp = true;

    /**
     * 获取当月签到记录
     *
     * @param array $param
     *
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author   [小码哥]
     */
    public function getMonthSign($param = [])
    {
        return $this->where($param)->order(['create_time'=>'ASC'])->select();
    }

    /**
     * 签到
     *
     * @param     $user_id
     * @param int $money
     *
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author   [小码哥]
     */
    public function addSign($user_id, $money = 0)
    {
        $is_sign = $this->is_sign($user_id);
        if(true !== $is_sign){
            return $is_sign;
        }
        try{
            $response = $this->allowField(true)->save(['user_id' => $user_id, 'money' => $money]);
            if($response){
                return ['code' => 200, 'data' => null, 'msg' => '签到成功'];
            }
            return ['code' => 0, 'data' => null, 'msg' => '签到失败'];
        }catch(PDOException $e){
            return ['code' => 0, 'data' => null, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 检测今日是否已经签到
     *
     * @param $user_id
     *
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author   [小码哥]
     */
    public function is_sign($user_id)
    {
        $where    = [
            'user_id'     => $user_id,
            'create_time' => ['between time', [date('Y-m-d 0:0:0'), date('Y-m-d 23:59:59')]]
        ];
        $response = $this->where($where)->find();
        if($response){
            return ['code' => 0, 'data' => null, 'msg' => '今日已签、明日再来'];
        }
        return true;
    }
}